import sys
import json
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QTableWidget, QTableWidgetItem, QPushButton, QMessageBox, QCheckBox, QAbstractItemView

class MVPJsonEditor(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('MVP JSON 编辑器')
        self.resize(1200, 600)
        self.layout = QVBoxLayout()
        self.setLayout(self.layout)

        self.table = QTableWidget()
        self.table.setSelectionBehavior(QAbstractItemView.SelectRows)  # 设置为行选择
        self.table.setDragDropMode(QAbstractItemView.NoDragDrop)  # 禁用表格内部拖动
        self.table.setDragEnabled(False)
        self.table.setAcceptDrops(False)
        self.table.setDropIndicatorShown(False)
        self.table.verticalHeader().setSectionsMovable(True)  # 允许拖动行号
        self.layout.addWidget(self.table)

        button_layout = QHBoxLayout()
        self.add_button = QPushButton('新增MVP')
        self.delete_button = QPushButton('删除MVP')
        self.save_button = QPushButton('保存文件')
        button_layout.addWidget(self.add_button)
        button_layout.addWidget(self.delete_button)
        button_layout.addWidget(self.save_button)
        self.layout.addLayout(button_layout)

        self.add_button.clicked.connect(self.add_entry)
        self.delete_button.clicked.connect(self.delete_entry)
        self.save_button.clicked.connect(self.save_json)

        # 自动加载 mvp.json
        self.load_json('mvp.json')

    def load_json(self, file_name):
        try:
            with open(file_name, 'r', encoding='utf-8') as file:
                data = json.load(file)
                self.populate_table(data['data'])
        except Exception as e:
            QMessageBox.critical(self, "错误：", f"错误信息: {e}")

    def populate_table(self, data):
        self.table.setRowCount(len(data))
        self.table.setColumnCount(12)
        self.table.setHorizontalHeaderLabels(['ID', 'MvpId', '等级', '名称', '图片名', '刷新时间(分)', '种族', '属性', '体型', '位置', '区域', '显示'])

        for row, mvp in enumerate(data):
            self.table.setItem(row, 0, QTableWidgetItem(mvp.get('id', '')))
            self.table.setItem(row, 1, QTableWidgetItem(str(mvp.get('mvpid', ''))))  # 确保 mvpid 是字符串
            self.table.setItem(row, 2, QTableWidgetItem(str(mvp.get('lv', ''))))
            self.table.setItem(row, 3, QTableWidgetItem(mvp.get('name', '')))
            self.table.setItem(row, 4, QTableWidgetItem(mvp.get('img', '')))
            self.table.setItem(row, 5, QTableWidgetItem(str(mvp.get('time', ''))))
            self.table.setItem(row, 6, QTableWidgetItem(mvp.get('race', '')))
            self.table.setItem(row, 7, QTableWidgetItem(mvp.get('attr', '')))
            self.table.setItem(row, 8, QTableWidgetItem(mvp.get('size', '')))
            self.table.setItem(row, 9, QTableWidgetItem(mvp.get('loc', '')))
            self.table.setItem(row, 10, QTableWidgetItem(mvp.get('label', '')))
            # 使用 QCheckBox 选择 true 或 false
            visible_checkbox = QCheckBox()
            visible_checkbox.setChecked(mvp.get('visible', True))
            visible_checkbox.setStyleSheet("QCheckBox::indicator { width: 15px; height: 15px; }")
            self.table.setCellWidget(row, 11, visible_checkbox)

        # 调整列宽以适应内容
        self.table.resizeColumnsToContents()

        # 设置每列的最小宽度为55
        for col in range(self.table.columnCount()):
            self.table.setColumnWidth(col, max(55, self.table.columnWidth(col)))

    def add_entry(self):
        row_count = self.table.rowCount()
        self.table.insertRow(row_count)
        for col in range(11):
            self.table.setItem(row_count, col, QTableWidgetItem(''))
        visible_checkbox = QCheckBox()
        self.table.setCellWidget(row_count, 11, visible_checkbox)

    def delete_entry(self):
        selected_rows = set(index.row() for index in self.table.selectedIndexes())
        for row in sorted(selected_rows, reverse=True):
            self.table.removeRow(row)

    def save_json(self):
        try:
            data = {'data': []}
            for visual_row in range(self.table.rowCount()):
                # 获取当前可视化顺序的行号
                actual_row = self.table.verticalHeader().logicalIndex(visual_row)
                mvp = {
                    'id': self.table.item(actual_row, 0).text(),
                    'mvpid': int(self.table.item(actual_row, 1).text() or 0),
                    'lv': int(self.table.item(actual_row, 2).text() or 0),
                    'name': self.table.item(actual_row, 3).text(),
                    'img': self.table.item(actual_row, 4).text(),
                    'time': int(self.table.item(actual_row, 5).text() or 0),
                    'race': self.table.item(actual_row, 6).text(),
                    'attr': self.table.item(actual_row, 7).text(),
                    'size': self.table.item(actual_row, 8).text(),
                    'loc': self.table.item(actual_row, 9).text(),
                    'label': self.table.item(actual_row, 10).text(),
                    'visible': self.table.cellWidget(actual_row, 11).isChecked()
                }
                data['data'].append(mvp)

            with open('mvp.json', 'w', encoding='utf-8') as file:
                json.dump(data, file, ensure_ascii=False, indent=4)
            QMessageBox.information(self, "信息", "mvp.json文件成功保存！")
        except Exception as e:
            QMessageBox.critical(self, "错误：", f"错误信息: {e}")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    editor = MVPJsonEditor()
    editor.show()
    sys.exit(app.exec())
